<template>
  <div>
     <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <el-table border stripe :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
              <el-row class="bdbot" :class="index == 0 ?'bdtop':''" v-for="(item,index) in scope.row.children" :key="item.id">
                  <el-col :span="5">
                      <el-tag>{{item.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                     <el-row :class="i2 === 0 ? '':'bdtop'" v-for="(item2,i2) in item.children" :key="item2.id">
                         <el-col :span="8">
                             <el-tag type="success">{{item2.authName}}</el-tag>
                             <i class="el-icon-caret-right"></i>
                         </el-col>
                         <el-col :span="11">
                            <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeTag(scope.row,  item3.id)">{{item3.authName}}</el-tag>
                         </el-col>
                     </el-row>
                  </el-col>
              </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="320">
         <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="Editdialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="delRoles(scope.row.id)">删除</el-button>
          <el-button @click="showSetRights(scope.row)" type="warning" size="mini" icon="el-icon-setting">分配权限</el-button>
         </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
  title="分配权限"
  :visible.sync="setRightsDialog"
  width="30%"
  @close="setRightsClose">
  <el-tree
  :data="rightsList"
  :props="treeProps"
  show-checkbox default-expand-all node-key="id"
  :default-checked-keys="defaultkeys"
  ref="tree">
</el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsDialog = false">取 消</el-button>
    <el-button type="primary" @click="setRights(roleId)">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改信息"
  :visible.sync="EditdialogVisible"
  width="30%">
    <el-form :model="roleData" ref="editRoleForm" :rules="AddRolesRules">
      <el-form-item label="角色名称" prop="roleName" label-width="100px">
        <el-input type="text" v-model="roleData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc" label-width="100px">
        <el-input type="text" v-model="roleData.roleDesc"></el-input>
      </el-form-item>
    </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="EditdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRights">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="添加角色"
  :visible.sync="AddRolesdialogVisible"
  width="30%">
  <el-form label-width="120px" :rules="AddRolesRules" :model="AddRolesForm">
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="AddRolesForm.roleName"></el-input>
    </el-form-item>
    <el-form-item label="角色描述" prop="roleDesc">
      <el-input v-model="AddRolesForm.roleDesc"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="AddRolesdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="AddRolesPost">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      //   dialogVisible: false,
      setRightsDialog: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //  是否选中的id
      defaultkeys: [],
      roleId: [],
      EditdialogVisible: false,
      roleData: {},
      AddRolesdialogVisible: false,
      AddRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      AddRolesRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 4, max: 10, message: '长度在 4 到 10 个字符', trigger: 'blur' }]
      }
    }
  },

  created () {
    this.getRoles()
  },

  methods: {
    //  渲染页面
    async getRoles () {
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
    },
    //  删除权限标签
    removeTag (Rol, RigId) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.axios.delete(`roles/${Rol.id}/rights/${RigId}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        Rol.children = res.data
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    async showSetRights (row) {
      // 将id保存起来 用来后面添加权限
      this.roleId = row.id
      const { data: res } = await this.axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rightsList = res.data
      this.setRightsDialog = true
      this.getAllkeys(row)
    },
    //  获取选中的id
    getAllkeys (row) {
      //  当循环到第三层时不需要再次循环 将选中的id保存下来
      if (!row.children) return this.defaultkeys.push(row.id)
      row.children.forEach(item => {
        this.getAllkeys(item)
      })
    },
    //  关闭树图弹窗树图清空
    setRightsClose () {
    //   this.setRightsDialog = false
      this.defaultkeys = ''
    },
    async setRights (id) {
      //  角色id getCheckedKeys getHalfCheckedKeys
    //   console.log(this.roleId)
      //   console.log()
    //   console.log(...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys())
      //  将获取的数组进行分解合并为一个数组
      const arrlist = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      const roleIdlist = arrlist.join(',')
      const { data: res } = await this.axios.post(`roles/${id}/rights`, { rids: roleIdlist })
      if (res.meta.status !== 200) return this.$message.error('数据更新失败')
      this.getRoles()
      this.setRightsDialog = false
      this.$message.success('数据更新成功')
    },
    Editdialog (row) {
      this.EditdialogVisible = true
      //  必须进行深拷贝 浅拷贝导致地址一样 修改时将页面也修改
      this.roleData = JSON.parse(JSON.stringify(row))
    },
    editRights () {
      // this.EditdialogVisible = true
      const id = this.roleData.id
      this.$refs.editRoleForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.axios.put(`roles/${id}`, { roleName: this.roleData.roleName, roleDesc: this.roleData.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改信息失败')
        this.EditdialogVisible = false
        this.getRoles()
        this.$message.success('修改信息成功')
      })
    },
    //  添加角色功能
    addRoles () {
      this.AddRolesdialogVisible = true
    },
    //  添加角色功能
    async AddRolesPost () {
      const { data: res } = await this.axios.post('roles', {
        roleName: this.AddRolesForm.roleName,
        roleDesc: this.AddRolesForm.roleDesc
      })
      if (res.meta.status !== 201) return this.$message.error('添加角色失败')
      this.AddRolesdialogVisible = false
      this.getRoles()
      this.$message.success('添加角色成功')
    },
    //  删除角色功能
    delRoles (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.axios.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRoles()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.bdtop {
    border-top: 1px solid #eee;
}
.bdbot {
    border-bottom: 1px solid #eee;
}
.el-tag {
    margin: 5px;
}
.el-row {
    display: flex;
    align-items: center;
}
</style>
